import {
  Button,
  Popconfirm,
  Switch,
  Table,
  message,
  Input,
  Space,
  Modal,
  Select,
} from "antd";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  createUser,
  deleteUser,
  listRoles,
  listUsers,
  modifyPassword,
  resetPassword,
  updateUserRole,
} from "../../api/ckgl";
import { Role, User } from "../../api/type/ckgl";
import AddRolesToUserModal from "./componets/AddRolesToUserModal";
import AddUserModal from "./componets/NewUserModal";
import ResetPasswordModal from "./componets/ResetPasswordModal";
const { Option } = Select;

const ListUsers = () => {
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [page, setPage] = useState<number>(1);
  const [size] = useState<number>(10);
  const [isAddUserModalVisible, setIsAddUserModalVisible] =
    useState<boolean>(false);
  const [isRolesToUserdModalVisible, setIsRolesToUserdModalVisible] =
    useState<boolean>(false);
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [roles, setRoles] = useState<Role[]>([]);
  const [roleId, setRoleId] = useState<undefined | number>(undefined);
  let navigate = useNavigate();

  const hanldeClickAdd = () => {
    setIsAddUserModalVisible(true);
  };

  const handleChangePage = (pg: number) => {
    setPage(pg);
  };

  useEffect(() => {
    if (localStorage?.role_code !== "admin") {
      navigate("/home");
    }
  }, []);

  function copyToClipboard(text: string) {
    const el = document.createElement("textarea");
    el.value = text;
    el.setAttribute("readonly", "");
    el.style.position = "absolute";
    el.style.left = "-9999px";
    document.body.appendChild(el);
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);
  }

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
      render: (_: any, record: any) => (
        <div onClick={() => copyToClipboard(record.username)}>
          {record.username}
        </div>
      ),
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
      render: (_: any, record: any) => (
        <div onClick={() => copyToClipboard(record.email)}>{record.email}</div>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "create_time",
      key: "create_time",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      render: (_: any, record: any) => <>{record.role.name}</>,
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      render: (_: any, record: any) => (
        <>
          <Button
            onClick={() => {
              console.log("record", record);

              setCurrentUser(record);
              setIsRolesToUserdModalVisible(true);
            }}
            style={{ marginRight: "10px" }}
            type="link"
          >
            修改用户角色
          </Button>

          <Popconfirm
            okText="确认"
            cancelText="取消"
            title="你确认要重置用户嘛?"
            onConfirm={() => {
              handleResetPassword(record);
            }}
          >
            <Button type="link">重置密码</Button>
          </Popconfirm>
          <Popconfirm
            okText="确认"
            cancelText="取消"
            title="你确认要删除该用户嘛?"
            onConfirm={() => {
              handleDeleteUser(record);
            }}
          >
            <Button danger type="link">
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  const handleDeleteUser = (record: any) => {
    // TODO: 这里自己不能删除自己
    deleteUser({
      user_id: record.id,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error("删除失败");
        return;
      }
      message.success(`删除${record.username}用户成功`);
      // 更新当前
      reset(page);
    });
  };

  const getListRoles = () => {
    listRoles({
      page: 1,
      size: 100,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { roles } = res.data;
      setRoles(roles);
    });
  };

  const getListUsers = (page: number) => {
    console.log("page", page);
    listUsers({
      page,
      size,
      role_id: roleId,
    }).then((res: any) => {
      console.log(res);
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      // admin(系统管理员)，purchaser（采购人员），m-admin（物资管理员），picker（领物），visitor（游客）
      const { users, total } = res.data;
      setList(users);
      setTotal(total);
    });
  };

  const reset = (page: number) => {
    getListUsers(page);
  };

  const handleAddUser = (values: {
    // 必填
    username: string;
    // 必填
    email: string;
    // 必填
    password: string;
    role_code: string;
  }) => {
    console.log("values", values);
    const { username, email, password, role_code } = values;
    createUser({
      username,
      email,
      password,
      role_code,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      message.success("添加用户成功");
      setIsAddUserModalVisible(false);
      // 更新当前
      reset(page);
    });
  };

  const showModal = (content: string) => {
    Modal.confirm({
      title: "重置之后的秘密",
      content: content,
      onOk() {
        console.log("点击了确定");
      },
      onCancel() {
        console.log("点击了取消");
      },
    });
  };

  const handleResetPassword = async (record: any) => {
    const { id } = record;
    let restRes: any = await resetPassword({
      user_id: id,
    });
    if (restRes?.code !== 0) {
      message.error(restRes.msg);
      return;
    }
    message.success("重置成功");
    showModal(restRes.data.password);
    console.log("restRes", restRes);
  };

  useEffect(() => {
    getListUsers(page);
    !roles.length && getListRoles();
  }, [page, roleId]);

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <Select
          placeholder="请选择用户角色"
          allowClear
          onChange={(value: number) => {
            console.log("value", value);
            setRoleId(value);
          }}
          style={{
            width: 200,
          }}
        >
          {roles.map((role) => (
            <Option key={role.id} value={role.id}>
              {role.name}
            </Option>
          ))}
        </Select>
        <Button
          style={{ marginTop: "7px", marginLeft: "10px" }}
          onClick={hanldeClickAdd}
          size="large"
          type="primary"
        >
          添加用户
        </Button>
      </div>

      <Table
        dataSource={list}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize: size,
          defaultCurrent: 1,
          onChange: handleChangePage,
          total: total,
        }}
      />
      <AddUserModal
        roles={roles}
        title={"添加用户"}
        visible={isAddUserModalVisible}
        onCancel={() => setIsAddUserModalVisible(false)}
        onOk={handleAddUser}
        defaultValue={{}}
      />
      <AddRolesToUserModal
        visible={isRolesToUserdModalVisible}
        onCancel={() => setIsRolesToUserdModalVisible(false)}
        onOk={(values: any) => {
          const { role_id } = values;
          const { id } = currentUser;
          updateUserRole({
            user_id: id,
            role_id,
          })
            .then((res: any) => {
              if (res?.code !== 0) {
                message.error("更新失败");
                return;
              }

              reset(page);
            })
            .finally(() => {
              setIsRolesToUserdModalVisible(false);
            });
        }}
        defaultValue={
          {
            role_id: currentUser?.role.id || "",
          } || ({} as any)
        }
        roles={roles}
      />
    </div>
  );
};

export default ListUsers;
